package com.tian.core.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;


/**
 * 解析资源文件
 * </br>
 */
public class PropertiesUtil {

    private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);

    public static final String DEFAULT_PROP_SUFFIX = ".properties";


    private PropertiesUtil() {

    }

    public static String readProperty(String key, String fileName) {
        return readProperty(key, "", fileName);
    }


    public static String readProperty(String key, String defaultValue, String fileName) {
        Properties p = getProperties(fileName);
        String value = p.getProperty(key);
        value = value == null ? defaultValue : value;
        return value;
    }

    private static Properties getProperties(String fileName) {
        Properties p = new Properties();
        InputStream is = null;
        try {
            is = PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName + DEFAULT_PROP_SUFFIX);
            if (is != null) {
                p.load(is);
            }
        } catch (IOException e) {
            logger.error("文件读取错误", e);
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                logger.error("输入流关闭异常", e);
            }
        }
        return p;
    }

}
